﻿using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Elmah;
using FinancePortal.Business.Infraestructureb;
using FinancePortal.Web.IoC;

namespace FinancePortal.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
            filters.Add(new ElmahHandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",
                "{controller}.aspx/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
              );

            routes.MapRoute(
              "Root",
              "",
              new { controller = "Home", action = "Index", id = "" }
            );
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            DependencyResolver.SetResolver(new UnityDependencyResolver()); 
        }

        public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e)
        {
            var httpException = e.Exception as HttpException;
            if (httpException != null && httpException.GetHttpCode() == 404)
            {
                e.Dismiss();
            }
        }

        protected void Session_Start()
        { }

        protected void Application_BeginRequest()
        {
            //var uow = DependencyResolver.Current.GetService<IUnitOfWork>();
            //uow.CurrentSession = new NHibernateHelper().SessionFactory.OpenSession();
            //IUnityContainer container = UnityDependencyResolver.Container;
            //var session = new NHibernateHelper().SessionFactory.OpenSession();
            //container.RegisterInstance<ISession>(session, new ContainerControlledLifetimeManager());
        }

        protected void Application_EndRequest()
        {
            //using (DependencyResolver.Current as IDisposable) { }
            //var session = DependencyResolver.Current.GetService<UnitOfWork>();
            
            //if (session != null)
            //    session.Dispose();
        }
    }
}